package cc.vv.lkimagecomponent2.loaderplugin.util;

import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.webkit.URLUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import cc.vv.lkimagecomponent2.LKImage;
import cc.vv.lkimagecomponent2.lib.Contants;
import cc.vv.lkimagecomponent2.loaderplugin.LoadConfig;
import cc.vv.lklibrary.log.LogOperate;


/**
 * 工具类
 *
 * @author dup dupeng@vv.cc
 * @data 2018/3/14
 */

public class ImageUtil {
    private static Handler mainHandler;

    public static Handler getMainHandler() {
        if (mainHandler == null) {
            synchronized (ImageUtil.class) {
                if (mainHandler == null) {
                    mainHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        return mainHandler;
    }


    public static int dip2px(float dipValue) {
        final float scale = LKImage.getContext().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 获取文件真实的格式。
     *
     * @param file
     * @return
     */
    public static String getRealType(File file) {
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            byte[] b = new byte[4];
            try {
                is.read(b, 0, b.length);
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("FFD8FF")) {
                return "jpg";
            } else if (type.contains("89504E47")) {
                return "png";
            } else if (type.contains("47494638")) {
                return "gif";
            } else if (type.contains("49492A00")) {
                return "tif";
            } else if (type.contains("424D")) {
                return "bmp";
            }
            return type;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将传入的string 看情况转化为uri，如果不匹配，返回null
     * <br>
     * 这里匹配：1.http 2.resId  3.filePath  4.contentProvider  5.assets  6.raw
     *
     * @param loadConfig
     * @return
     */
    public static Uri buildUriByType(LoadConfig loadConfig) {
        if (!TextUtils.isEmpty(loadConfig.getUrl()) && URLUtil.isValidUrl(loadConfig.getUrl())) {
            //如果是uri格式
            return Uri.parse(loadConfig.getUrl());
        } else if (!TextUtils.isEmpty(loadConfig.getUrl()) && !URLUtil.isValidUrl(loadConfig.getUrl())) {
            //如果不是url格式,那就看是不是文件路径
            File file = new File(loadConfig.getUrl());
            if (file != null && file.exists() && !file.isDirectory()) {
                return Uri.fromFile(file);
            }
        } else {
        }

        if (loadConfig.getResId() > 0) {
            return Uri.parse(Contants.ANDROID_RESOURCE + loadConfig.getContext().getPackageName() + Contants.FOREWARD_SLASH + loadConfig.getResId());
        }

        if (!TextUtils.isEmpty(loadConfig.getFilePath())) {
            File file = new File(loadConfig.getFilePath());
            if (file.exists()) {
                return Uri.fromFile(file);
            }
        }

        if (!TextUtils.isEmpty(loadConfig.getContentProvider())) {
            String content = loadConfig.getContentProvider();
            if (!content.startsWith(Contants.ANDROID_CONTENT)) {
                content = Contants.ANDROID_CONTENT + content;
            }
            return Uri.parse(content);
        }

        if (!TextUtils.isEmpty(loadConfig.getAssertspath())) {
            String assets = loadConfig.getAssertspath();
            if (!assets.startsWith(Contants.ASSETS_PATH)) {
                assets = Contants.ASSETS_PATH + assets;
            }
            return Uri.parse(assets);
        }

        if (loadConfig.getRawId() > 0) {
            return Uri.parse(Contants.ANDROID_RESOURCE + loadConfig.getContext().getPackageName() + Contants.FOREWARD_SLASH + loadConfig.getRawId());
        }

        return null;
    }


    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}
